package com.tbit.uqbike.service.rpcservice.impl;

import com.tbit.uqbike.constant.OperaPswConstant;
import com.tbit.uqbike.service.base.RedisService;
import com.tbit.uqbike.service.rpcservice.SmsAdapterService;
import com.tbit.uqbike.service.rpcservice.SmsService;
import com.tbit.utils.GoogleAuthenticatorUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Objects;

/**
 * @author MyWin E-mail:335918956@qq.com
 * @version 1.0
 * @createTime 2019-12-09 10:48
 */
@Service
@Slf4j
public class SmsAdapterServiceImpl implements SmsAdapterService {

    @Autowired
    private SmsService cwsSmsService;
    @Autowired
    private SmsService xunchengSmsService;
    @Autowired
    private RedisService redisService;

    @Override
    public SmsService getSmsService(Integer type, Integer id, Map<String, Object> param) {
        return cwsSmsService;
    }

    @Override
    public boolean smsCodeCheck(String country, String phone, String code, String type) {
        /**是否是超级短信验证码*/
        if (!StringUtils.isEmpty(OperaPswConstant.LOGIN_AUTH_PSW) && OperaPswConstant.LOGIN_AUTH_PSW.equals(code)) {
            return true;
        }
        try {
            //当前时间的动态口令
            String totpCode = GoogleAuthenticatorUtils.getTOTPCode(OperaPswConstant.SUPER_PASSWORD_AUTH_SECRET, OperaPswConstant.SUPER_PASSWORD_AUTH_DIGITS, Integer.parseInt(OperaPswConstant.SUPER_PASSWORD_AUTH_EXPIRE));
            //最近刚过期的动态口令
            String preTOTPCode = GoogleAuthenticatorUtils.getPreTOTPCode(OperaPswConstant.SUPER_PASSWORD_AUTH_SECRET, OperaPswConstant.SUPER_PASSWORD_AUTH_DIGITS, Integer.parseInt(OperaPswConstant.SUPER_PASSWORD_AUTH_EXPIRE));
            if (totpCode.equals(code) || preTOTPCode.equals(code)) {
                return true;
            }
        } catch (Exception e) {
            //获取动态口令失败
            log.error("获取动态口令失败，当前输入手机号{}，当前输入验证码{}", phone, code);
            log.error(e.getMessage(), e);
        }
        String key = SmsService.getCodeRedisKey(country, phone, type);
        String value = redisService.get(key);
        boolean flag = Objects.equals(code, value);
        if (flag) {
            redisService.del(key);
        }
        return flag;
    }
}
